/* 
 * drag 1.0
 * create by kehailin
 * date 2017/12/22
 * æå¨æ»å
 */
(function($){
    $.fn.drag = function(options){
        var x, drag = this, isMove = false, defaults = {
        };
        var options = $.extend(defaults, options);
        //æ·»å èæ¯ï¼æå­ï¼æ»å
        var html = '<div class="drag_bg"></div>'+
                    '<div class="drag_text" onselectstart="return false;" unselectable="on">æå¨æ»åéªè¯</div>'+
                    '<div class="handler handler_bg"></div>';
        this.append(html);
        
        var handler = drag.find('.handler');
        var drag_bg = drag.find('.drag_bg');
        var text = drag.find('.drag_text');
        var maxWidth = drag.width() - handler.width();  //è½æ»å¨çæå¤§é´è·
        
        //é¼ æ æä¸æ¶åçxè½´çä½ç½®
        handler.mousedown(function(e){
            isMove = true;
            x = e.pageX - parseInt(handler.css('left'), 10);
        });
        
        //é¼ æ æéå¨ä¸ä¸æç§»å¨æ¶ï¼ç§»å¨è·ç¦»å¤§äº0å°äºæå¤§é´è·ï¼æ»åxè½´ä½ç½®ç­äºé¼ æ ç§»å¨è·ç¦»
        $(document).mousemove(function(e){
            var _x = e.pageX - x;
            if(isMove){
                if(_x > 0 && _x <= maxWidth){
                    handler.css({'left': _x});
                    drag_bg.css({'width': _x});
                }else if(_x > maxWidth){  //é¼ æ æéç§»å¨è·ç¦»è¾¾å°æå¤§æ¶æ¸ç©ºäºä»¶
                    dragOk();
                }
            }
        }).mouseup(function(e){
            isMove = false;
            var _x = e.pageX - x;
            if(_x < maxWidth){ //é¼ æ æ¾å¼æ¶ï¼å¦ææ²¡æè¾¾å°æå¤§è·ç¦»ä½ç½®ï¼æ»åå°±è¿ååå§ä½ç½®
                handler.css({'left': 0});
                drag_bg.css({'width': 0});
            }
        });
        
        //æ¸ç©ºäºä»¶
        function dragOk(){
            handler.removeClass('handler_bg').addClass('handler_ok_bg');
            text.text('éªè¯éè¿');
            drag.css({'color': '#fff'});
            handler.unbind('mousedown');
            $(document).unbind('mousemove');
            $(document).unbind('mouseup');
            $("#drag").attr("on-off","on");//éªè¯æ¯å¦ææ½
        }
    };
})(jQuery);


